from time import strftime
from djfacet.constants import DJ_SHOWLOGS
from settings import DEBUG




def djfacetlog(stringa, override = False):
	""" simple utility function that prints a debug string is DJ_SHOWLOGS is True
		If DEBUG= True it assumes we're using runserver, otherwise it tries to write it to a file
		and fails silently 
	"""
	if DJ_SHOWLOGS or override:
		if stringa == 'noise':
			stringa = "\n%s\n" % ("*&*^" * 100)
		if DEBUG:
			try:
				print ">>[%s]djfacetDebug>>: %s"	% (strftime("%Y-%m-%d %H:%M:%S"), stringa)
			except:
				pass
		else:
			file = "/tmp/djfacet_log.txt"
			try:
				handle = open(file,"a")
				now = "--%s--\n"	% strftime("%Y-%m-%d %H:%M:%S")
				handle.write( now + stringa +"\n")
				handle.close()
			except:
				pass









##################
#  Wed Nov 17 11:55:14 GMT 2010
#  The following two methods help visualizing hierarchical trees based on MPTT 
#
##################


# once we obtained the tree_dict with the IDs, here we check again that only the values with updated howmany are passed
# OPTIMIZE? ? ? change the method in facet.py ? 

def tree_visualizer(root, tree_dict, res, facet, facetgroup, facetvalues):
	for x in tree_dict[root]:
		facetvalue = [v for v in facetvalues if v.id == x]
		if facetvalue:
			res += """<li style="font-size:12px;"><a id="%s_%d" class="%s" >%s (%d)</a>""" % (facetgroup.uniquename, 
				facetvalue[0].id, facet.name, facetvalue[0].displayname,  facetvalue[0].howmany)
		else:
			facetvalue = facet.get_facetvalue_from_id(x)
			res += """<li>%s""" % facetvalue.displayname  #<span style="color: #2C528B;">%s</span>
		if tree_dict.get(x):
			# djfacetlog("noise")
			res += "<ul>" + tree_visualizer(x, tree_dict, '', facet, facetgroup, facetvalues) + "</ul>"
		res += "</li>"
	return res
	
	
	
	
def render_tree_string(facetvalues, facet, facetgroup):
	if True:
		stringa = ""
		#  the dict cointains the tree structure with IDs only
		djfacetlog("\n STARTING LOADING THE TREE............... \n")
		mydict = facet.recursive_tree_forfacetvalue_list(facetvalues)
		djfacetlog("\n DONE LOADING THE TREE \n")
		# stringa ideally should be built inside the template, using a recursive model.. TODO
		djfacetlog("\n STARTING VISUALIZING THE TREE............... \n")
		stringa = tree_visualizer(0, mydict, "", facet, facetgroup, facetvalues)
		djfacetlog("\n DONE VISUALIZING THE TREE \n")			
	return stringa 
	
	
	
	


def findmin(rangen, n):
	e = 0
	while e < n:
		e += rangen
		# returns the one before
	return e - rangen

def findmax(rangen, n):
	e = 0
	while e < n:
		e += rangen
		# returns the one after
	return e

def buildranges(amin, amax, rangeval):
	"""Retunrs a list of tuples, with the string-range first and then
	 the numbers in a tuple: [('990-1020', (990, 1020)), ('1020-1050', (1020, 1050))]  """
	r = []
	allvalues = range(amin, amax, rangeval)
	for index, item in enumerate(allvalues):
		if (index + 1) < len(allvalues):
			a = "%d-%d" % (item, allvalues[index + 1])
			r.append((a, (item, allvalues[index + 1])))
	return r


	



##################
#  Mon Sep 20 12:59:39 BST 2010
#  just a bunch of utilities... 
#  @ copyright michele pasin
##################



def best_encoding(x_to_encode):
	out = None
	if type(x_to_encode) == type(1) or type(x_to_encode) == type(1L):  # type int or long
		out = str(x_to_encode)
	else:
		try:
			out = x_to_encode.encode('utf-8')		
		except:
			try:
				out = x_to_encode.encode('iso-8859-1')
			except:
				raise Exception("** could not encode **")
				# out = "** could not encode **"
	return out


def blank_or_string(s):
	"""If it's empty, output the string blank"""
	if not s.strip():
		return 'blank'
	return s


def preview_string(s, length):
	"""If we have a value, returns the first [length] chars of the string.."""
	if s:
		if	len(s) < length:
			result = unicode(s) 
		else:
			result = unicode(s)[0:length] + "..."
		return result

def isint(s):
	"""checks if a string is a number"""
	try:
		return int(s)
	except ValueError:
		return False




def split_list_into_two(somelist):
	x = len(somelist)
	z = x/2
	res1 = somelist[:(x -z)]
	res2 = somelist[(x -z):]
	return [res1, res2]



def group_list_items_by_two(lista, listaexit= None):
	lista_x = []
	listaexit = listaexit or []
	if lista:
		lista_x.extend(lista)
		lista_x.reverse()		
		first_el = lista_x.pop()
		if len(lista_x) == 0:
			second_el = None 
		else:
			second_el = lista_x.pop()
		listaexit.append([first_el, second_el]) 
		if lista[2:]:
			group_list_items_by_two(lista[2:], listaexit)
		#print(listaexit)
		return listaexit



filler = ["value_%s" % (i) for i in range(10)]


# given a center, returns a list of the neighbouring numbers according to the paramenters passed
def paginator_helper(center, max, howmany=5, interval=1, min=1, ):
	if center - howmany > min:
		min = center - howmany
	if center + howmany < max:
		max = center + howmany
	return range(min, (max + 1), interval)





#  helper for django models : NEVER USED
def get_or_new(model, somename):
	"""helper method"""
	try:
		# if there's an object with same name, we keep that one!
		obj = model.objects.get(name= somename)
		print "++++++++++++++++++++++++++ found existing obj:	%s"	 % (obj)
	except:
		obj = model(name = somename)
		obj.save()
		print "======= created new obj:	  %s"  % (obj)
	return obj





def list_difference(list1, list2):
	""" returns the difference between two lists """
	return [x for x in list1+list2 if x not in list1 or x not in list2]







